package com.panan.GenTool;

import com.panan.Config;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

public class GenMapperXml {

    public GenMapperXml() {

        String content = parse();

        try {
            File directory = new File("");
            String path=this.getClass().getResource("").getPath();
            String outputPath = directory.getAbsolutePath()+ "/src/main/java/"+ Config.map.get("mapper.xml.location").replace(".", "/")+"/"+Config.map.get("entity.mapper.name")+".xml";
            FileWriter fw = new FileWriter(outputPath);
            PrintWriter pw = new PrintWriter(fw);
            pw.println(content);
            pw.flush();
            pw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 功能：生成Mapper主体代码
     */
    private String parse() {
        StringBuffer sb = new StringBuffer();
        if("true".equalsIgnoreCase(Config.map.get("mapper.xml"))) {
            sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n");
            sb.append("<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\n\r\n");
            sb.append("<mapper namespace=\""+Config.map.get("mapper.basemapper.location")+"."+Config.map.get("entity.mapper.name")+"\">\r\n\n");
            sb.append("    <SELECT id=\"findAll\" resultType=\""+Config.map.get("entity.calss.output.package")+"."+Config.map.get("entity.name")+"\">\n");
            sb.append("\t\tSELECT \r\n");
            sb.append("\t\t\t");
            List<String> list = Config.colMap.get("entity.column");
            for (int i=0;i<list.size();i++) {
                if(i<list.size()){
                    sb.append(list.get(i)+",");
                }
                if(i==list.size()-1){
                    sb.append(list.get(i));
                }

            }
            sb.append("\r\n\t\tFROM\r\n");
            sb.append("\t\t\t"+Config.map.get("database.table")+"\r\n");
            sb.append("\t</SELECT>\r\n");
            sb.append("</mapper>");
        }else{

        }
        //System.out.println(sb.toString());
        return sb.toString();
    }

}
